package com.cmys.money.cloudshop.service.template;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.cmys.money.cloudshop.util.file.FileUtils;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service("templateService")
public class TemplateServiceImpl implements TemplateService {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@Override
	public void createPage(String templatePath, String templateName, String htmlPath, String htmlName, Map<String, Object> map) {
		try {
	    	// 通过指定模板名获取FreeMarker模板实例
			String templateFile = FileUtils.changePathSeparator(templatePath + templateName);
	        Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(templateFile);
	        // FreeMarker通过Map传递动态数据，解析模板并替换动态数据
			String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
			logger.debug(htmlText);
			String htmlFile = FileUtils.changePathSeparator(htmlPath + htmlName);
			OutputStream os = new FileOutputStream(htmlFile);
			String encoding = tpl.getEncoding();
			logger.debug("使用编码: " + encoding);
			FileUtils.outPutFile(htmlText, os, encoding);
	    } catch (IOException e) {
	    	logger.error(e);
	    } catch (TemplateException e) {
	    	logger.error(e);
	    }
		
	}

}
